{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Exploring new features of OpenAI's GPT-5 model\n",
        "In this tutorial, we’ll explore the new capabilities introduced in OpenAI’s latest model, GPT-5. The update brings several powerful features, including the Verbosity parameter, Free-form Function Calling, Context-Free Grammar (CFG), and Minimal Reasoning. We’ll look at what they do and how to use them in practice."
      ],
      "metadata": {
        "id": "0qPyCGH9kZfD"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Installing the libraries"
      ],
      "metadata": {
        "id": "jkYWMnFtk5xw"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "collapsed": true,
        "id": "q8x8PSindCkp",
        "outputId": "387686f9-529f-4d28-e87e-e6da46f7b95d"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: pandas in /usr/local/lib/python3.11/dist-packages (2.2.2)\n",
            "Requirement already satisfied: openai in /usr/local/lib/python3.11/dist-packages (1.98.0)\n",
            "Requirement already satisfied: numpy>=1.23.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (2.0.2)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (2.9.0.post0)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas) (2025.2)\n",
            "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas) (2025.2)\n",
            "Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from openai) (4.10.0)\n",
            "Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/dist-packages (from openai) (1.9.0)\n",
            "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.28.1)\n",
            "Requirement already satisfied: jiter<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from openai) (0.10.0)\n",
            "Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.11/dist-packages (from openai) (2.11.7)\n",
            "Requirement already satisfied: sniffio in /usr/local/lib/python3.11/dist-packages (from openai) (1.3.1)\n",
            "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.11/dist-packages (from openai) (4.67.1)\n",
            "Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.11/dist-packages (from openai) (4.14.1)\n",
            "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/dist-packages (from anyio<5,>=3.5.0->openai) (3.10)\n",
            "Requirement already satisfied: certifi in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (2025.8.3)\n",
            "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx<1,>=0.23.0->openai) (1.0.9)\n",
            "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)\n",
            "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)\n",
            "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic<3,>=1.9.0->openai) (0.4.1)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
          ]
        }
      ],
      "source": [
        "!pip install pandas openai"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "To get an OpenAI API key, visit https://platform.openai.com/settings/organization/api-keys and generate a new key. If you're a new user, you may need to add billing details and make a minimum payment of $5 to activate API access."
      ],
      "metadata": {
        "id": "Mq8L0riYn4j6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "from getpass import getpass\n",
        "os.environ['OPENAI_API_KEY'] = getpass('Enter OpenAI API Key: ')"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "d1Pm2XPldfNg",
        "outputId": "555e9446-6cb3-4f36-c9a1-3befc2ff1c8d"
      },
      "execution_count": 2,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter OpenAI API Key: ··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 1. Verbosity Parameter\n",
        "The Verbosity parameter lets you control how detailed the model’s replies are without changing your prompt.\n",
        "\n",
        "* low → Short and concise, minimal extra text.\n",
        "\n",
        "* medium (default) → Balanced detail and clarity.\n",
        "\n",
        "* high → Very detailed, ideal for explanations, audits, or teaching."
      ],
      "metadata": {
        "id": "o62lhdSplBBg"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "import pandas as pd\n",
        "from IPython.display import display\n",
        "\n",
        "client = OpenAI()\n",
        "\n",
        "question = \"Write a poem about a detective and his first solve\"\n",
        "\n",
        "data = []\n",
        "\n",
        "for verbosity in [\"low\", \"medium\", \"high\"]:\n",
        "    response = client.responses.create(\n",
        "        model=\"gpt-5-mini\",\n",
        "        input=question,\n",
        "        text={\"verbosity\": verbosity}\n",
        "    )\n",
        "\n",
        "    # Extract text\n",
        "    output_text = \"\"\n",
        "    for item in response.output:\n",
        "        if hasattr(item, \"content\"):\n",
        "            for content in item.content:\n",
        "                if hasattr(content, \"text\"):\n",
        "                    output_text += content.text\n",
        "\n",
        "    usage = response.usage\n",
        "    data.append({\n",
        "        \"Verbosity\": verbosity,\n",
        "        \"Sample Output\": output_text,\n",
        "        \"Output Tokens\": usage.output_tokens\n",
        "    })\n"
      ],
      "metadata": {
        "id": "rH-6cYw7drrt"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Create DataFrame\n",
        "df = pd.DataFrame(data)\n",
        "\n",
        "# Display nicely with centered headers\n",
        "pd.set_option('display.max_colwidth', None)\n",
        "styled_df = df.style.set_table_styles(\n",
        "    [\n",
        "        {'selector': 'th', 'props': [('text-align', 'center')]},  # Center column headers\n",
        "        {'selector': 'td', 'props': [('text-align', 'left')]}     # Left-align table cells\n",
        "    ]\n",
        ")\n",
        "\n",
        "display(styled_df)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 508
        },
        "id": "9w4a2GrQeAxv",
        "outputId": "09e3904b-913b-42fc-a85e-bd426c013d59"
      },
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "<pandas.io.formats.style.Styler at 0x780f680632d0>"
            ],
            "text/html": [
              "<style type=\"text/css\">\n",
              "#T_75bf2 th {\n",
              "  text-align: center;\n",
              "}\n",
              "#T_75bf2 td {\n",
              "  text-align: left;\n",
              "}\n",
              "</style>\n",
              "<table id=\"T_75bf2\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th class=\"blank level0\" >&nbsp;</th>\n",
              "      <th id=\"T_75bf2_level0_col0\" class=\"col_heading level0 col0\" >Verbosity</th>\n",
              "      <th id=\"T_75bf2_level0_col1\" class=\"col_heading level0 col1\" >Sample Output</th>\n",
              "      <th id=\"T_75bf2_level0_col2\" class=\"col_heading level0 col2\" >Output Tokens</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th id=\"T_75bf2_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
              "      <td id=\"T_75bf2_row0_col0\" class=\"data row0 col0\" >low</td>\n",
              "      <td id=\"T_75bf2_row0_col1\" class=\"data row0 col1\" >He learned the city by its silences — rain in gutters, neon sighing,\n",
              "a paper cup spinning in a puddle like a clock hand.\n",
              "His coat still smelled of factory floors and new breath;\n",
              "the badge felt heavier than the coin his father gave him.\n",
              "\n",
              "The case was crooked in the way people hide small things:\n",
              "a borrowed alibi, a burned receipt, a photograph folded in a pocket.\n",
              "He sat with evidence like a patient animal, waiting.\n",
              "Clues arrived as soft as footsteps — a stamp, a thread of tobacco.\n",
              "\n",
              "A witness stammered a truth between apologies;\n",
              "a ledger opened like a palm, numbers falling into place.\n",
              "He fit the fragments together: motive, time, an overheard lie.\n",
              "It clicked — quiet as a door unlocked — and the room exhaled.\n",
              "\n",
              "The first solve did not make him a hero, only a clearer-eyed man.\n",
              "He learned how guilt looks when stripped of theater,\n",
              "how relief can be a small, weary thing.\n",
              "He went home with mud on his shoes and a new respect for the dark.</td>\n",
              "      <td id=\"T_75bf2_row0_col2\" class=\"data row0 col2\" >731</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th id=\"T_75bf2_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
              "      <td id=\"T_75bf2_row1_col0\" class=\"data row1 col0\" >medium</td>\n",
              "      <td id=\"T_75bf2_row1_col1\" class=\"data row1 col1\" >The badge was new and cold against my palm,\n",
              "a metal question I had not yet learned to ask.\n",
              "Night draped the block in the same tired coat\n",
              "the city wore to pretend nothing had happened.\n",
              "\n",
              "They sent me to a room where words had been used up—\n",
              "a window steamed with someone else's breath,\n",
              "a child's shoe tucked beneath the radiator,\n",
              "a smear of something that did not belong. I knelt\n",
              "and felt for patterns as if for pulse.\n",
              "\n",
              "Clues are small kindnesses from the world, or cruelties;\n",
              "the first one looked like an accident until it didn't.\n",
              "I lined facts up like dominoes and watched the truth\n",
              "give way beneath the weight of evidence.\n",
              "There was a man who said the right thing twice,\n",
              "a woman who blinked when she thought no one watched,\n",
              "a ledger scribbled in a hand that trembled.\n",
              "\n",
              "Solving it was not a sudden light but a sequence:\n",
              "the slow importuning of questions, the soft unspooling\n",
              "of alibis, the way lies fold to fit themselves\n",
              "like paper in a drawer. The confession came\n",
              "out of a cigarette and a long dry silence,\n",
              "not with thunder but with the ordinary sound\n",
              "of someone unloading what they could not carry.\n",
              "\n",
              "When they pinned the name on the board,\n",
              "my hands stopped shaking and started remembering—\n",
              "how the street smelled then, how rain makes the neon honest,\n",
              "how a small shoe sits forever at the lip of a radiator.\n",
              "The first solve gave me a key and a wound:\n",
              "I learned how to pry at seams and watch people show\n",
              "themselves as if by accident. I learned the cost.\n",
              "\n",
              "Since that night, each case begins the same way—\n",
              "with a cold badge and a reluctant city—and ends\n",
              "with a quiet window opened to let truth out,\n",
              "or a door shut on the things we cannot make clean.</td>\n",
              "      <td id=\"T_75bf2_row1_col2\" class=\"data row1 col2\" >1017</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th id=\"T_75bf2_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
              "      <td id=\"T_75bf2_row2_col0\" class=\"data row2 col0\" >high</td>\n",
              "      <td id=\"T_75bf2_row2_col1\" class=\"data row2 col1\" >He learned to listen the way some men learn to pray:\n",
              "not with words, but with the elbows of his palms,\n",
              "laying them on cold surfaces of kitchen tables and car hoods,\n",
              "feeling the small, honest tremors of things left behind.\n",
              "\n",
              "The case came in on a slow, rainy Tuesday,\n",
              "a missing watch, brass and grief in equal measure—\n",
              "an old man's heirloom, wound tight with decades,\n",
              "gone from a dresser like a punctuation mark erased.\n",
              "\n",
              "They joked about it at the station, chewed stale coffee,\n",
              "but he kept the file like an unfinished sentence.\n",
              "He read the witness statements as if they were maps,\n",
              "tracing the same crooked lines until the ink faded true.\n",
              "A pattern sat patient in the margins: the neighbor’s cat, a lemon peel on the sink,\n",
              "a thread of blue lint tangled in the hem of a coat.\n",
              "\n",
              "He learned that clues are shy things, shy like children,\n",
              "that you invite out by the tone of your question, the steadiness of your gaze.\n",
              "So he went back to the house at dusk, smelling the rain and the lemon peel,\n",
              "running his thumb along drawer edges, reading dust like a palm reader,\n",
              "noting where the light had been allowed to fall.\n",
              "\n",
              "There in the seam of an old atlas book—how ridiculous—he found the watch,\n",
              "nestled like a secret between pages of places no one promised to visit.\n",
              "It was cooler than he expected, stamped by time, wound low but not dead.\n",
              "A bus ticket fluttered out, folded thrice, a single name written in a handwriting that trembled.\n",
              "\n",
              "The solving came quiet, sideways, like a door closing behind him.\n",
              "He followed the ticket, a trail of small, ordinary things—an unpaid phone bill,\n",
              "a hymn hummed under breath in a shelter doorway, the way a man orders coffee black.\n",
              "He learned to read the gravity of gestures: the way someone avoids eye contact,\n",
              "the way they set an extra plate at table and let it cool.\n",
              "\n",
              "When he finally returned the watch, the old man held it like a relic of his own bones.\n",
              "There were no brass bands of applause, only two men and the slow, mutual unspooling\n",
              "of relief that makes a room smell like freshly washed linen.\n",
              "\"How did you know?\" the old man asked, voice thin as thread.\n",
              "\n",
              "He felt younger than he had when the badge was pinned.\n",
              "He wanted to tell him it was the lemon peel, the cat, the way dust refused to stay where it had fallen,\n",
              "but found himself answering in a simpler truth:\n",
              "\"I listened,\" he said. \"And then I kept listening.\"\n",
              "\n",
              "That night he walked home under a sky that smelled of rain and notebooks.\n",
              "He had not expected triumph—just the steady, small proof that a thing could be put back where it belonged.\n",
              "His first solve folded into him like a secret pocket—warm, private, surprising.\n",
              "He understood then that every case is a kind of telling: of loss, of habit, of the way people arrange their lives\n",
              "so the smallest missing thing pulls the rest into sharp focus.\n",
              "\n",
              "He slept like someone who had learned how to breathe again.\n",
              "And in the morning, the watch on his desk ticked, patient and indifferent,\n",
              "marking hours he had not yet earned, reminding him that every solution is only ever the beginning\n",
              "of another, quieter question whispering its way into the dark.</td>\n",
              "      <td id=\"T_75bf2_row2_col2\" class=\"data row2 col2\" >1263</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The output tokens scale roughly linearly with verbosity: low (731) → medium (1017) → high (1263)."
      ],
      "metadata": {
        "id": "2PTaOoB_lLhJ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 2. Free-Form Function Calling\n",
        "Free-form function calling lets GPT-5 send raw text payloads—like Python scripts, SQL queries, or shell commands—directly to your tool, without the JSON formatting used in GPT-4.\n",
        "\n",
        "This makes it easier to connect GPT-5 to external runtimes such as:\n",
        "\n",
        "* Code sandboxes (Python, C++, Java, etc.)\n",
        "\n",
        "* SQL databases (outputs raw SQL directly)\n",
        "\n",
        "* Shell environments (outputs ready-to-run Bash)\n",
        "\n",
        "* Config generators"
      ],
      "metadata": {
        "id": "X2iPtXVtliH0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "\n",
        "client = OpenAI()\n",
        "\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-5-mini\",\n",
        "    input=\"Please use the code_exec tool to calculate the cube of the number of vowels in the word 'pineapple'\",\n",
        "    text={\"format\": {\"type\": \"text\"}},\n",
        "    tools=[\n",
        "        {\n",
        "            \"type\": \"custom\",\n",
        "            \"name\": \"code_exec\",\n",
        "            \"description\": \"Executes arbitrary python code\",\n",
        "        }\n",
        "    ]\n",
        ")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "k18ESSIOgi-a",
        "outputId": "9e738745-f956-49b1-c3ec-5859899edec8"
      },
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[ResponseReasoningItem(id='rs_6896258896d4819581704bc526cbe75f01010511b1d90111', summary=[], type='reasoning', encrypted_content=None, status=None), ResponseOutputMessage(id='ctc_6896258aeb4c8195acbd14063b08687701010511b1d90111', content=None, role=None, status='completed', type='custom_tool_call', call_id='call_OGv2f6N10xi3dF8MW4AsLE5C', input='word = \"pineapple\"\\nvowels = set(\"aeiouAEIOU\")\\ncount = sum(1 for ch in word if ch in vowels)\\ncube = count ** 3\\nprint(count)\\nprint(cube)\\n', name='code_exec')]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(response.output[1].input)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RHw-RAlmgx_W",
        "outputId": "c6fcce3b-a11b-42ad-999b-fd297512b024"
      },
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "word = \"pineapple\"\n",
            "vowels = set(\"aeiouAEIOU\")\n",
            "count = sum(1 for ch in word if ch in vowels)\n",
            "cube = count ** 3\n",
            "print(count)\n",
            "print(cube)\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "This output shows GPT-5 generating raw Python code that counts the vowels in the word pineapple, calculates the cube of that count, and prints both values. Instead of returning a structured JSON object (like GPT-4 typically would for tool calls), GPT-5 delivers plain executable code. This makes it possible to feed the result directly into a Python runtime without extra parsing."
      ],
      "metadata": {
        "id": "kr5puo3TmJkJ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3. Context-Free Grammar (CFG)\n",
        "A Context-Free Grammar (CFG) is a set of production rules that define valid strings in a language. Each rule rewrites a non-terminal symbol into terminals and/or other non-terminals, without depending on the surrounding context.\n",
        "\n",
        "CFGs are useful when you want to strictly constrain the model’s output so it always follows the syntax of a programming language, data format, or other structured text — for example, ensuring generated SQL, JSON, or code is always syntactically correct.\n",
        "\n",
        "For comparison, we’ll run the same script using GPT-4 and GPT-5 with an identical CFG to see how both models adhere to the grammar rules and how their outputs differ in accuracy and speed."
      ],
      "metadata": {
        "id": "CwjwuFs2mK_h"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "import re\n",
        "\n",
        "client = OpenAI()\n",
        "\n",
        "email_regex = r\"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$\"\n",
        "\n",
        "prompt = \"Give me a valid email address for John Doe. It can be a dummy email\"\n",
        "\n",
        "# No grammar constraints — model might give prose or invalid format\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-4o\",  # or earlier\n",
        "    input=prompt\n",
        ")\n",
        "\n",
        "output = response.output_text.strip()\n",
        "print(\"GPT Output:\", output)\n",
        "print(\"Valid?\", bool(re.match(email_regex, output)))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "NlsvtCaqhcl5",
        "outputId": "4ef54d47-6735-4445-f170-acbff5992dab"
      },
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "GPT Output: Sure, here's a test email you can use for John Doe: johndoe@example.com\n",
            "Valid? False\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "\n",
        "client = OpenAI()\n",
        "\n",
        "email_regex = r\"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$\"\n",
        "\n",
        "prompt = \"Give me a valid email address for John Doe. It can be a dummy email\"\n",
        "\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-5\",  # grammar-constrained model\n",
        "    input=prompt,\n",
        "    text={\"format\": {\"type\": \"text\"}},\n",
        "    tools=[\n",
        "        {\n",
        "            \"type\": \"custom\",\n",
        "            \"name\": \"email_grammar\",\n",
        "            \"description\": \"Outputs a valid email address.\",\n",
        "            \"format\": {\n",
        "                \"type\": \"grammar\",\n",
        "                \"syntax\": \"regex\",\n",
        "                \"definition\": email_regex\n",
        "            }\n",
        "        }\n",
        "    ],\n",
        "    parallel_tool_calls=False\n",
        ")\n",
        "\n",
        "print(\"GPT-5 Output:\", response.output[1].input)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "UK7P-WPSjRtg",
        "outputId": "46dad620-2ed4-46d6-c0d1-a85df7b7e723"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "GPT-5 Output: john.doe@example.com\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "This example shows how GPT-5 can adhere more closely to a specified format when using a Context-Free Grammar.\n",
        "\n",
        "With the same grammar rules, GPT-4 produced extra text around the email address (\"Sure, here's a test email you can use for John Doe: johndoe@example.com\"), which makes it invalid according to the strict format requirement.\n",
        "\n",
        "GPT-5, however, output exactly john.doe@example.com, matching the grammar and passing validation. This demonstrates GPT-5’s improved ability to follow CFG constraints precisely."
      ],
      "metadata": {
        "id": "eZVrtFL6mjUU"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4. Minimal Reasoning\n",
        "Minimal reasoning mode runs GPT-5 with very few or no reasoning tokens, reducing latency and delivering a faster time-to-first-token.\n",
        "\n",
        "It’s ideal for deterministic, lightweight tasks such as:\n",
        "\n",
        "* Data extraction\n",
        "\n",
        "* Formatting\n",
        "\n",
        "* Short rewrites\n",
        "\n",
        "* Simple classification\n",
        "\n",
        "Because the model skips most intermediate reasoning steps, responses are quick and concise. If not specified, the reasoning effort defaults to medium."
      ],
      "metadata": {
        "id": "hhls4CfFmnCR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import time\n",
        "from openai import OpenAI\n",
        "\n",
        "client = OpenAI()\n",
        "\n",
        "prompt = \"Classify the given number as odd or even. Return one word only.\"\n",
        "\n",
        "start_time = time.time()  # Start timer\n",
        "\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-5\",\n",
        "    input=[\n",
        "        { \"role\": \"developer\", \"content\": prompt },\n",
        "        { \"role\": \"user\", \"content\": \"57\" }\n",
        "    ],\n",
        "    reasoning={\n",
        "        \"effort\": \"minimal\"  # Faster time-to-first-token\n",
        "    },\n",
        ")\n",
        "\n",
        "latency = time.time() - start_time  # End timer\n",
        "\n",
        "# Extract model's text output\n",
        "output_text = \"\"\n",
        "for item in response.output:\n",
        "    if hasattr(item, \"content\"):\n",
        "        for content in item.content:\n",
        "            if hasattr(content, \"text\"):\n",
        "                output_text += content.text\n",
        "\n",
        "print(\"--------------------------------\")\n",
        "print(\"Output:\", output_text)\n",
        "print(f\"Latency: {latency:.3f} seconds\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JrkNFTHvkSLl",
        "outputId": "7d7aaf81-ca69-415e-c737-4eb1555ded9f"
      },
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "--------------------------------\n",
            "Output: odd\n",
            "Latency: 1.021 seconds\n"
          ]
        }
      ]
    }
  ]
}